package com.dongjiantong.web.protal.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.CacheTime;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.redis.RedisUtil;
import com.dongjiantong.common.utils.StringUtil;

import com.dongjiantong.common.utils.UUIDUtil;
import com.dongjiantong.common.utils.WebUtil;
import com.dongjiantong.common.web.sso.LoginToken;
import com.dongjiantong.common.web.sso.WebLoginToken;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.user.enums.UserEnum;
import com.dongjiantong.user.model.LogsUserLogin;
import com.dongjiantong.user.model.MzUser;
import com.dongjiantong.user.service.LogsUserLoginService;
import com.dongjiantong.user.service.MzUserService;
import com.dongjiantong.web.protal.handler.SessionsModel;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

/**
 * 客户管理登录
 * Created by cao on 2017/11/8.
 */
@Slf4j
@OpenBean
public class LoginController {

    @Reference(version = "1.0.0")
    public MzUserService mzUserService;

    @Reference(version = "1.0.0")
    public LogsUserLoginService logsUserLoginService;

    @OpenMethod(
            key = "web.user.login",
            paramNames = {"userName","password"},
            httpMethods = RequestMethod.POST
    )
    public Response<WebLoginToken> Login(String userName, String password)
    {
      //
        if (StringUtil.isEmpty(userName)) {
            throw new OPServerException(HttpCode.BAD_REQUEST.getCode(),"用户名不能为空");
        }
        if (StringUtil.isEmpty(password)) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"登录密码不能为空");
        }
        MzUser mzUser=null;

         // 用户名密码登录

          mzUser = this.doLogin(userName, password);



        String sid = WebUtil.generateId(UUIDUtil.UUID());


        // 登录成功记录 session
        Map<String, Object> sessionContext = Maps.newHashMap();
        sessionContext.put(SessionsModel.USER_ID, mzUser.getId());
        sessionContext.put(SessionsModel.DEVICE_ID, sid);

        String sessionKey=SessionsModel.TOKEN_PREFIX+":"+sid;
        RedisUtil.setEX(sessionKey,sessionContext, CacheTime.ONE_SHORTDAY.getTime());



        //Web角色
//        List<RoleAppUser> roleAppUserList =  roleAppUserService.queryRoleAppByUserId(mzUser.getId());
//
//        List<RoleModel> roleModelList = Lists.newArrayList();
//        RoleModel roleModel;
//        for (RoleAppUser roleAppUser:roleAppUserList) {
//
//            roleModel = new RoleModel();
//            roleModel.setRoleCode(roleAppUser.getAppRole());
//            roleModel.setRoleName(roleAppUser.getAppRoleName());
//
//            roleModelList.add(roleModel);
//        }



        // 返回登录的凭证
        WebLoginToken webLoginToken = new WebLoginToken();
        webLoginToken.setUserId(mzUser.getId());
        webLoginToken.setRealName(mzUser.getRealname());
        webLoginToken.setMobile(mzUser.getMobile());
        webLoginToken.setWebRole(null);
        webLoginToken.setExpiredAt(DateTime.now().plusSeconds(CacheTime.ONE_SHORTDAY.getTime())
                .toString(DateTimeFormat.forPattern("yyyyMMddHHmmss")));
        webLoginToken.setSessionId(sid);


        return Response.ok(webLoginToken);

    }

    public MzUser doLogin(String userName, String password) {

        Response<MzUser> mzUserResponse = mzUserService.checkLogin(userName, password, UserEnum.LOGIN_WEB);

        if (!mzUserResponse.isSuccess()) {
            throw new OPServerException(HttpCode.LOGIN_FAIL,mzUserResponse.getMessage());
        }

        //记录登录日志
        LogsUserLogin logsUserLogin = new LogsUserLogin();
        logsUserLogin.setUserId(mzUserResponse.getResult().getId());
        logsUserLogin.setLoginTime(new Date());
        logsUserLogin.setLoginIp(WebUtil.clientIp());
        logsUserLogin.setLoginArea(WebUtil.getAreaByIP(WebUtil.clientIp()));
        logsUserLogin.setLoginFrom(UserEnum.LOGIN_WEB.getCode());
        logsUserLogin.setLoginDeviceId("");
        logsUserLogin.setLoginDeviceName(WebUtil.browserName());
        logsUserLogin.setLoginDeviceVer(WebUtil.browserVer());

        logsUserLoginService.insert(logsUserLogin);


        return mzUserResponse.getResult();

    }

}
